import {
  listScoresToTeacherUsingPost,
  markExceptionByAdminUsingPost,
} from '@/services/student-management-system/fenshumokuai';
import { SearchOutlined } from '@ant-design/icons';
import { Badge, Button, Form, Input, message, Popconfirm, Select, Space, Table } from 'antd';

import {
  AntdStatus,
  getTagStatusByStatus,
  getTextByStatus,
  ScoreStatus,
} from '@/common/ScoreStatus';
import moment from 'moment';
import React, { useEffect, useState } from 'react';

const ScoreAudit: React.FC = () => {
  const initSearchParam = {
    current: 1,
    pageSize: 6,
    sortField: 'createTime',
    sortOrder: 'desc',
  };

  // 存储下拉数据
  interface optionsType {
    value: number | undefined;
    label: string | undefined;
  }

  const [queryParam, setQueryParam] = useState<API.QueryScoreDTO>({ ...initSearchParam });
  const [dataSource, setDataSource] = useState<API.ScoreVO[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [statusOptions, setStatusOptions] = useState<optionsType[]>([]);

  const handleMark = async (record: API.ScoreVO) => {
    // 修改状态
    const res = await markExceptionByAdminUsingPost({
      id: record.id,
      status: ScoreStatus.EXCEPTION,
    });
    if (res.code === 200) {
      message.success('标记成功，请通知教师查看异常成绩');
      // 刷新页面
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      await getScoreList();
    } else {
      message.error('标记失败：' + res.msg);
    }
  };

  const handleAudit = async (record: API.ScoreVO, isPass: boolean) => {
    // 通过还是拒绝
    const res = await markExceptionByAdminUsingPost({
      id: record.id,
      status: isPass ? ScoreStatus.NORMAL : ScoreStatus.EXCEPTION,
    });
    if (res.code === 200) {
      message.success('审核成功');
      // 刷新页面
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      await getScoreList();
    } else {
      message.error('审核失败：' + res.msg);
    }
  };

  const columns = [
    { title: '分数ID', dataIndex: 'id', key: 'id' },
    { title: '学生', dataIndex: 'studentName', key: 'studentName' },
    { title: '学生ID', dataIndex: 'studentId', key: 'studentId' },
    { title: '班级', dataIndex: 'className', key: 'className' },
    { title: '课程名称', dataIndex: 'courseName', key: 'courseName' },
    { title: '分数', dataIndex: 'score', key: 'score' },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Badge status={getTagStatusByStatus(status) as AntdStatus} text={getTextByStatus(status)} />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'options',
      width: '120px',
      render: (_: any, record: any) => (
        <div>
          {record.status === ScoreStatus.REVIEWING ? (
            <div>
              <Button
                size={'small'}
                type={'primary'}
                style={{ marginBottom: '5px' }}
                onClick={() => {
                  handleAudit(record, true);
                }}
              >
                通过
              </Button>
              <Popconfirm
                title="审核"
                description="确认拒绝通过吗 ？"
                onConfirm={() => {
                  handleAudit(record, false);
                }}
                okText="Yes"
                cancelText="No"
              >
                <Button size={'small'} type={'default'}>
                  拒绝
                </Button>
              </Popconfirm>
            </div>
          ) : (
            <Space>
              <Popconfirm
                title="标记"
                description="确认标记为异常成绩 ？"
                onConfirm={() => {
                  handleMark(record);
                }}
                okText="Yes"
                cancelText="No"
              >
                <Button size="small">标记</Button>
              </Popconfirm>
            </Space>
          )}
        </div>
      ),
    },
  ];

  const getScoreList = async () => {
    const res = await listScoresToTeacherUsingPost(queryParam);
    if (res.code === 200) {
      message.success('获取数据成功');
      setDataSource(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } else {
      message.error('获取数据失败：' + res.msg);
    }
  };

  useEffect(() => {
    getScoreList();

    setStatusOptions([
      { value: 0, label: '异常' },
      { value: 1, label: '正常' },
      { value: 2, label: '审核中' },
    ]);
  }, [queryParam]);

  return (
    <div className="ManageScore">
      <Form layout="inline" onFinish={(values) => setQueryParam({ ...initSearchParam, ...values })}>
        <Form.Item name="courseName" label="课程名称">
          <Input style={{ width: '130px' }} placeholder="请输入课程名称" />
        </Form.Item>
        <Form.Item name="className" label="班级名称">
          <Input style={{ width: '130px' }} placeholder="请输入班级名称" />
        </Form.Item>
        <Form.Item name="studentId" label="学生学号">
          <Input style={{ width: '130px' }} placeholder="请输入学生学号" />
        </Form.Item>

        <Form.Item name="status" label="状态">
          <Select placeholder="选择状态" optionFilterProp="label" options={statusOptions} allowClear={true}/>
        </Form.Item>

        <Form.Item>
          <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>

      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          total,
          current: queryParam.current,
          pageSize: queryParam.pageSize,
          onChange: (current, pageSize) => setQueryParam({ ...queryParam, current, pageSize }),
        }}
      />
    </div>
  );
};

export default ScoreAudit;
